/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.form;

import com.sun.mail.smtp.SMTPTransport;
import gui.ImageListShower;
import gui.form.MainForm;
import java.awt.Dimension;
import java.io.File;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.*;
import qviewer.ServiceManager;

/**
 *
 * @author OSIRIS
 */
public class SendEmailDialog extends javax.swing.JDialog implements Runnable {

    /**
     * Creates new form NewJDialog
     */
    private String user = "";
    private String pass = "";
    //   private File file;
    private List<File> files;
    DefaultListModel listModel = new DefaultListModel();

    public SendEmailDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        if (user.isEmpty()) {
            inputInfo();
        }
        ImageListShower imageList = ServiceManager.getInstance().getShower();
        files = imageList.getFiles();
        loadList();
    }

    private void loadList() {
        listFileAttack.removeAll();
        for (File file : files) {
            listModel.addElement(file);
        }
        listFileAttack.setModel(listModel);
    }

    private void inputInfo() {
        JTextField txtUserName = new JTextField();
        JPasswordField txtPassword = new JPasswordField();
        final JComponent[] inputs = new JComponent[]{
            new JLabel("User Name:"),
            txtUserName,
            new JLabel("Password:"),
            txtPassword
        };
        JOptionPane.showMessageDialog(null, inputs, "Login Google Mail", JOptionPane.PLAIN_MESSAGE);

        user = txtUserName.getText();
        pass = new String(txtPassword.getPassword());
        lbCurrentUser.setText(user);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        listFileAttack = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        lbCurrentUser = new javax.swing.JLabel();
        lbChangeUser = new javax.swing.JLabel();
        btnSendEmail = new javax.swing.JButton();
        btnDiscardEmail = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtEmailTo = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        txtEmailSubject = new javax.swing.JTextField();
        btnDeleteImage = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane3.setViewportView(listFileAttack);

        jLabel3.setText("List file Attack: ");
        jLabel3.setToolTipText("");

        lbCurrentUser.setText("curentUser");

        lbChangeUser.setForeground(new java.awt.Color(102, 102, 255));
        lbChangeUser.setText("changeUser");
        lbChangeUser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbChangeUserMouseClicked(evt);
            }
        });

        btnSendEmail.setText("Send");
        btnSendEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendEmailActionPerformed(evt);
            }
        });

        btnDiscardEmail.setText("Discard");
        btnDiscardEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDiscardEmailActionPerformed(evt);
            }
        });

        jLabel1.setText("To: ");

        txtEmailTo.setColumns(20);
        txtEmailTo.setRows(5);
        jScrollPane1.setViewportView(txtEmailTo);

        jLabel2.setText("Subject: ");

        btnDeleteImage.setText("Delete");
        btnDeleteImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteImageActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(185, 185, 185)
                        .addComponent(lbCurrentUser)
                        .addGap(34, 34, 34)
                        .addComponent(lbChangeUser))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnDiscardEmail)
                        .addGap(18, 18, 18)
                        .addComponent(btnSendEmail))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3))
                        .addGap(43, 43, 43)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(txtEmailSubject)
                                .addComponent(jScrollPane1)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnDeleteImage))))
                .addGap(35, 35, 35))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbChangeUser)
                    .addComponent(lbCurrentUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtEmailSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(btnDeleteImage)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSendEmail)
                    .addComponent(btnDiscardEmail)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSendEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendEmailActionPerformed
        Thread myThread = new Thread(this);
        myThread.start();
        this.setVisible(false);
    }//GEN-LAST:event_btnSendEmailActionPerformed

    private void btnDiscardEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDiscardEmailActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnDiscardEmailActionPerformed

    private void lbChangeUserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbChangeUserMouseClicked
        inputInfo();
    }//GEN-LAST:event_lbChangeUserMouseClicked

    private void btnDeleteImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteImageActionPerformed
        int index = listFileAttack.getSelectedIndex();
        if (index != -1) {
            listModel.remove(index);
        }
    }//GEN-LAST:event_btnDeleteImageActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SendEmailDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SendEmailDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SendEmailDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SendEmailDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                SendEmailDialog dialog = new SendEmailDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDeleteImage;
    private javax.swing.JButton btnDiscardEmail;
    private javax.swing.JButton btnSendEmail;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lbChangeUser;
    private javax.swing.JLabel lbCurrentUser;
    private javax.swing.JList listFileAttack;
    private javax.swing.JTextField txtEmailSubject;
    private javax.swing.JTextArea txtEmailTo;
    // End of variables declaration//GEN-END:variables

    @Override
    public void run() {

        MainForm mainForm = (MainForm) SwingUtilities.getRoot(this.getParent());
        JToolBar toolBar = mainForm.getjToolBarProcess();
        JLabel processMsg = new JLabel();
        processMsg.setText("Sending Images");
        toolBar.add(processMsg);
        JProgressBar processBar = new JProgressBar(0, 100);
        processBar.setSize(new Dimension(100, processBar.getHeight()));
        toolBar.add(processBar);
        toolBar.updateUI();

        try {
            //   JOptionPane.showInputDialog(this, "Nhập danh sách bạn bè");
            String from = user;
            String to = txtEmailTo.getText();
            String subject = txtEmailSubject.getText();
            String messageBody = "This is image attack with qViewer";
            Properties props = System.getProperties();

            props.put("mail.smtps.host", "smtp.gmail.com");
            props.put("mail.smtps.auth", "true");
            Session session = Session.getInstance(props, null);
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to, false));
            msg.setSubject(subject);

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(messageBody);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            for (int i = 0; i < listModel.getSize(); i++) {
                String file = listModel.get(i).toString();
                String[] fileNames = file.split("\\\\");
                String fileName = fileNames[fileNames.length - 1];
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(fileName);
                multipart.addBodyPart(messageBodyPart);
            }

            msg.setContent(multipart);
            SMTPTransport t =
                    (SMTPTransport) session.getTransport("smtps");
            t.connect("smtp.gmail.com", user, pass);
            processBar.setValue(30);
            t.sendMessage(msg, msg.getAllRecipients());
            processBar.setValue(100);
            processMsg.setText("Send mail success");
            t.close();
        } catch (MessagingException mex) {
            processMsg.setText("Send mail Error:" + mex.getMessage());
        }
        try {
            Thread.sleep(5000);
            toolBar.remove(processBar);
            toolBar.remove(processMsg);
            toolBar.updateUI();
        } catch (InterruptedException ex) {
            Logger.getLogger(SendEmailDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
